package utils

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
)


// GetFileMd5 获取文件MD5
func GetFileMd5(filename string) string {
	// 文件全路径名
	pFile, err := os.Open(filename)
	if err != nil {
		_ = fmt.Errorf("打开文件失败，filename=%v, err=%v", filename, err)
		return ""
	}
	defer func(pFile *os.File) {
		_ = pFile.Close()
	}(pFile)
	md5h := md5.New()
	_, _ = io.Copy(md5h, pFile)

	return hex.EncodeToString(md5h.Sum(nil))
}



// SelfMd5sum 获取程序自身的MD5
func SelfMd5sum() string {
	path, e := exec.LookPath(os.Args[0])
	if e != nil {
		log.Println(`Self md5sum error: look path fail:`, e)
		return ""
	}
	bs, e := ioutil.ReadFile(path)
	if e != nil {
		log.Println(`SelfMd5sum error: read file fail:`, e)
		return ""
	}
	sum := md5.Sum(bs)
	return hex.EncodeToString(sum[:])
}
